package com.eddie.community.service.impl;

import com.eddie.community.dao.LoginTicketMapper;
import com.eddie.community.dao.UserMapper;
import com.eddie.community.entity.LoginTicket;
import com.eddie.community.entity.User;
import com.eddie.community.service.UserService;
import com.eddie.community.util.CommunityConstant;
import com.eddie.community.util.CommunityUtil;
import com.eddie.community.util.MailClient;
import com.eddie.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /* @Autowired
     private LoginTicketMapper loginTicketMapper;*/
    @Autowired
    private RedisTemplate redisTemplate;

    //邮件客户端
    @Autowired
    private MailClient mailClient;

    //模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    public User findUserById(int id) {
        // return userMapper.selectById(id);
        User user = getCache(id);
        if (user == null) {
            user = initCache(id);
        }
        return user;
    }

    @Override
    public Map<String, Object> register(User user) {

        Map<String, Object> map = new HashMap<>();

        //空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空！");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "用户名不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword()) || user.getPassword().length() < 8) {
            map.put("passwordMsg", "密码不能为空 且 长度不能少于8位！");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }

        //验证账号（查重）
        User currentUser = userMapper.selectByName(user.getUsername());
        if (currentUser != null) {
            map.put("usernameMsg", "该用户名已存在！");
            return map;
        }
        currentUser = userMapper.selectByEmail(user.getEmail());
        if (currentUser != null) {
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }

        //注册用户
        //切割前六位随机字符为salt值
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        //激活码
        user.setActivationCode(CommunityUtil.generateUUID());
        //头像 随机
        int num = (int) (Math.random() * 100);
        //http://images.nowcoder.com/head/11t.png
        user.setHeaderUrl("http://images.nowcoder.com/head/" + num + "t.png");
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        //发送激活邮件
        Context context = new Context();
        context.setVariable("username", user.getUsername());
        context.setVariable("email", user.getEmail());
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);
        return map;

    }

    @Override
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 2) {
            return CommunityConstant.REPEATED_ACTIVATION;
        } else if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1);
            clearCache(userId);
            return CommunityConstant.ACTIVATION_SUCCESSFUL;
        } else {
            return CommunityConstant.ACTIVATION_FAILED;
        }
    }

    @Override
    public Map<String, Object> login(String username, String password, int expired) {
        Map<String, Object> map = new HashMap<>();

        //空值判断
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "username 不能为空！");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "username 不能为空！");
            return map;
        }

        //验证用户
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "账号不存在！");
            return map;
        }
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "账号未激活！");
            return map;
        }
        String md5Password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(md5Password)) {
            map.put("passwordMsg", "密码错误！");
            return map;
        }
   /*     //如果ticket没失效，无须做以下操作
        LoginTicket currentTicket = loginTicketMapper.selectByUserId(user.getId());
        if (currentTicket != null |curren) {

        }
*/
        //生成凭证 并保存
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expired * 1000));
        //loginTicketMapper.insert(loginTicket);
        //使用redis插入ticket
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey, loginTicket);
        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    @Override
    public void logout(String ticket) {
        // loginTicketMapper.updateStatusByPrimaryKey(ticket, 1);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }

    @Override
    public LoginTicket findLoginTicketByTicket(String ticket) {
        //return loginTicketMapper.selectByTicket(ticket);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    @Override
    public int updateHeader(int userId, String headerUrl) {
        //return userMapper.updateHeader(userId, headerUrl);
        int rows = userMapper.updateHeader(userId, headerUrl);
        clearCache(userId);
        return rows;
    }

    @Override
    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }

    // 1.优先从缓存中取值
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    // 2.取不到时初始化缓存数据
    private User initCache(int userId) {
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    // 3.数据变更时清除缓存数据
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = this.findUserById(userId);
//授予的权限GrantedAuthority
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()) {//1为管理员 2 为超级管理员
                    case 1:
                        return CommunityConstant.AUTHORITY_MODERATOR;
                    case 2:
                        return CommunityConstant.AUTHORITY_ADMIN;
                    default:
                        return CommunityConstant.AUTHORITY_USER;
                }
            }
        });
        return list;
    }

    @Override
    public List<User> findHasRoleUser(int offset, int limit) {
        List<User> userList = userMapper.selectUserList(offset, limit);
        for (User u : userList) {
            User user = getCache(u.getId());
            if (user == null) {
                user = initCache(u.getId());
            }
        }
        return userList;
    }

    @Override
    public int changeType(int userId, int type) {
        clearCache(userId);
        return userMapper.updateTypeById(userId, type);
    }


    @Override
    public int changeStatus(int userId, int Status) {
        clearCache(userId);
        return userMapper.updateStatus(userId, Status);
    }

    @Override
    public int findStatus(int userId) {
        return userMapper.selectStatusById(userId);
    }
}
